package ConexaoDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import Entidade.Contato;
import Entidade.Grupo;

public class ContatoDao {

	private Connection connection;

	public ContatoDao() {
		this.connection = new ConnectionFactory().getConnection();
	}

	public void adiciona(Contato contato, Grupo grupo) {
		String sql = "insert into contatos" + "(nome,numero,email,id_grupo)"
				+ " values(?,?,?,?)";

		try {

			PreparedStatement stmt = connection.prepareStatement(sql);

			stmt.setString(1, contato.getNome());
			stmt.setString(2, contato.getNumero());
			stmt.setString(3, contato.getEmail());
			stmt.setLong(4, grupo.getIdgrupo());

			stmt.execute();
			stmt.close();

		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public boolean editar(Contato contato) {

		String sql = "update contatos set nome=?,numero=?,email=? where id=" + contato.getId();
		try {
			PreparedStatement stmt = connection.prepareStatement(sql);
			stmt.setString(1, contato.getNome());
			stmt.setString(2, contato.getNumero());
			stmt.setString(3, contato.getEmail());

			stmt.execute();
			stmt.close();
			return true;
		} catch (SQLException e) {
			throw new RuntimeException(e);

		}
	}

	public boolean delete(Contato contatos) {
		try {

			PreparedStatement stm = connection
					.prepareStatement("DELETE FROM contatos WHERE id="
							+ contatos.getId());
			stm.execute();
			stm.close();
			return true;
		} catch (Exception x) {
			return false;
		}
	}

	public ResultSet selectAll() {
		try {
			PreparedStatement stm = connection
					.prepareStatement("SELECT * FROM contatos");
			ResultSet result = stm.executeQuery();

			return result;
		} catch (Exception x) {
			return null;
		}
	}

}
